package org.lyxy.ssmdemo.service.impl;

import org.lyxy.ssmdemo.bean.User;
import org.lyxy.ssmdemo.dao.UserDao;
import org.lyxy.ssmdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;

    /*
    * 登录功能
    * 参数是 用户名
    * 查找出该用户的数据，然后再比对输入的密码和这个用户的密码是否一致
    */
    @Override
    public User findUser(User user) {
        User userResult = userDao.loginUser(user.getUserName());
        if (userResult != null && userResult.getUserPassword().equals(user.getUserPassword())){
            return userResult;
        }
        return null;
    }

    @Override
    public List<User> findUserByPage(int startIndex, int pageSize) {
        List<User> users = userDao.selectUserByPage(startIndex, pageSize);
        return users;
    }

    @Override
    public int findCountPage(int pageSize) {
        //查询总数
        double count = userDao.selectCountPage();
        //计算尾页 count/pageSize能得出总页数(不一定是整数) Math.ceil向上取整数
        int last = (int) Math.ceil(count/pageSize);
        return last;
    }

    @Override
    public int addUser(User user) {
        int count = userDao.selectByEmail(user);
        if (count > 0) {
            System.out.println("用户名已存在");
            return 0;
        } else {
            int result = userDao.insertUser(user);
            return result;
        }
    }


}
